package com.liu.stockmarket

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.liu.stockmarket.model.StockTransactionResult
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrl
import org.junit.Test
import java.io.IOException

class OkHttpTest {
    @Test
    fun searchStock() {
        val okHttpClient = OkHttpClient()
        val url = "https://searchapi.eastmoney.com/api/Info/Search"

        val parameterNames = mapOf(
            "appid" to "el1902262",
            "type" to "14",
            "token" to "CCSDCZSDCXYMYZYYSYYXSMDDSMDHHDJT",
            "and14" to "MultiMatch/Name,Code,PinYin/zgyy/true",
            "returnfields14" to "Name,Code,PinYin,MarketType,JYS,MktNum,JYS4App,MktNum4App,ID,Classify,IsExactMatch,SecurityType,SecurityTypeName",
            "pageIndex14" to "1",
            "pageSize14" to "30",
            "isAssociation14" to "false" + System.currentTimeMillis(),
        )


        val newBuilder = url.toHttpUrl().newBuilder()

        parameterNames.forEach {
            newBuilder.addEncodedQueryParameter(it.key, it.value)

        }


        val request = Request.Builder()
            .url(newBuilder.build())
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .addHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
            ).build()

        okHttpClient.newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    println("异常：${e.toString()}")
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.string()?.let {
                        println(it)
                        val type = object : TypeToken<Map<String, Any>>() {}.type
                        val fromJson = Gson().fromJson<Map<String, String>>(it, type)
                        println(fromJson)
                    }

                }
            })
        Thread.sleep(3000 * 10 * 10)
    }

    @Test
    fun stock() {
        /**
         * https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&
         * fields=f12,f13,f19,f14,f139,f148,f2,f4,f1,f125,f18,f3,f152,f5,f30,f31,f32,f6,f8,f7,f10,f22,f9,f112,f100,f88,f153
         * &secids=0.127043,1.601012,1.113048,0.002176,1.113051,1.118002,1.110081,1.113626,0.127040,0.128093,0.127029,1.601398,0.123120,1.000001
         */

        val okHttpClient = OkHttpClient()
        val url = "https://push2.eastmoney.com/api/qt/ulist.np/get"

        val parameterNames = mapOf(
            "fltt" to "2", // 1 上海  0深圳
            "fields" to "f12,f13,f19,f14,f139,f148,f2,f4,f1,f125,f18,f3,f152,f5,f30,f31,f32,f6,f8,f7,f10,f22,f9,f112,f100,f88,f153",
            "ut" to "f057cbcbce2a86e2866ab8877db1d059",
            "secids" to "0.005827",
        )


        val newBuilder = url.toHttpUrl().newBuilder()

        parameterNames.forEach {
            newBuilder.addEncodedQueryParameter(it.key, it.value)

        }


        val request = Request.Builder()
            .url(newBuilder.build())
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .addHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
            ).build()

        okHttpClient.newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    println("异常：${e.toString()}")
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.string()?.let {
                        println(it)
//                        val type = object : TypeToken<Map<String, Any>>() {}.type
//                        val fromJson = Gson().fromJson<Map<String, String>>(it, type)

                        val type = object : TypeToken<StockTransactionResult>() {}.type
                        val fromJson = Gson().fromJson<StockTransactionResult>(it, type)
                        println(fromJson)
                    }

                }
            })
        Thread.sleep(3000 * 10 * 10)
    }

    @Test
    fun kline() {
        val okHttpClient = OkHttpClient()
        val url = "https://push2his.eastmoney.com/api/qt/stock/kline/get"

        val parameterNames = mapOf(
            "secid" to "1.601398", // 1 上海  0深圳
            "klt" to "101",
            "fqt" to "1",
            "lmt" to "2", // 获取数量
            "end" to "20211014",
            "iscca" to "1",
            "fields1" to "f1,f2,f3,f4,f5",
            "fields2" to "f50,f51,f52,f53,f54,f55,f56,f57,f59,f60",
            "ut" to "f057cbcbce2a86e2866ab8877db1d059",
            "forcect" to "1",
        )


        val newBuilder = url.toHttpUrl().newBuilder()

        parameterNames.forEach {
            newBuilder.addEncodedQueryParameter(it.key, it.value)

        }


        val request = Request.Builder()
            .url(newBuilder.build())
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .addHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
            ).build()

        okHttpClient.newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    println("异常：${e.toString()}")
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.string()?.let {
                        println(it)
                        val type = object : TypeToken<Map<String, Any>>() {}.type
                        val fromJson = Gson().fromJson<Map<String, String>>(it, type)
                        println(fromJson)
                    }

                }
            })
        Thread.sleep(3000 * 10 * 10)
    }


    @Test
    fun fund() {
        val url = "https://fundmobapi.eastmoney.com/FundMNewApi/FundMNFInfo"

        val parameterNames = mapOf(
            "pageIndex" to "1",
            "pageSize" to "200",
            "plat" to "Android",
            "appType" to "ttjj",
            "product" to "EFund",
            "Version" to "1",
            "deviceid" to "5616d643-16a6-4f88-aef1-2f92767e5fbf",
            "Fcodes" to "161725"//005827

            )

        request(url, parameterNames)

        Thread.sleep(3000 * 10 * 10)
    }


    @Test
    fun fund2() {
        val url = "https://push2.eastmoney.com/api/qt/ulist.np/get"
        val parameterNames = mapOf(
            "fltt" to "2",
            "fields" to "f3",
            "secids" to "0.005827",
            "&_" to System.currentTimeMillis().toString(),
            )
        request(url,parameterNames)
        Thread.sleep(4000)
    }


    private fun request(url: String, parames: Map<String, String>) {
        val okHttpClient = OkHttpClient()

        val newBuilder = url.toHttpUrl().newBuilder()

        parames.forEach {
            newBuilder.addEncodedQueryParameter(it.key, it.value)

        }


        val request = Request.Builder()
            .url(newBuilder.build())
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .addHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38"
            ).build()

        okHttpClient.newCall(request)
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    println("异常：${e.toString()}")
                }

                override fun onResponse(call: Call, response: Response) {
                    response.body?.string()?.let {
                        println(it)
                        val type = object : TypeToken<Map<String, Any>>() {}.type
                        val fromJson = Gson().fromJson<Map<String, String>>(it, type)
                        println(fromJson)
                    }

                }
            })
    }
}